package com.youyun56.gps.android.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.util.Log;

/**
 * Http提供者
 * @author linwuhan
 *
 */
public class HttpProvider implements IHttpProvider{
	private static final String TAG = "HttpProvider";
	//超时设置
	private static final int TIMEOUT = 60 * 1000;
	//返回结果
	private String strResult;
	//http编码
	private String mStrCode = "UTF-8";
	//返回码
	private int responseCode;
	
	private static DefaultHttpClient httpClient;
	
	
	/**
	 * 获取返回码
	 * @return
	 */
	public int getResponseCode() {
		return responseCode;
	}
	/**
	 * 设置返回码
	 * @param responseCode
	 */
	public void setResponseCode(int responseCode) {
		this.responseCode = responseCode;
	}
	
	/**
	 * 获取返回结果
	 * @return
	 */
	public String getStrResult() {
		return strResult;
	}
	/**
	 * 设置返回结果
	 * @param strResult
	 */
	public void setStrResult(String strResult) {
		this.strResult = strResult;
	}
	/**
	 * 设置http编码 默认 utf-8
	 * @param strCode
	 */
	public void setCode(String strCode){
		mStrCode = strCode;
	}
	
	/**
	 * 初始化httpClient 
	 * 
	 * @return	执行结果
	 * 			
	 * 			1 成功 , 0 失败
	 */
	private int initHttpClient() {
		if(httpClient == null) {
			HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established.  
            HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.  
            HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT); 
            httpClient = new DefaultHttpClient(httpParameters);
		}
		return httpClient != null ? 1:0;
	}
	
	/**
	 *	 执行  http get 方法
	 * 
	 * @param url	http 链接
	 * 
	 * @return	返回方法执行状态
	 * 
	 * 			1 成功,0失败,-1异常,-2 responseCode != 200
	 */
	public int httpGet(String url) {
		
		int result = 1 ;
		
		if(url == null || url.length() <= 0) {
			return 0;
		}
		
		if(initHttpClient() == 0 || httpClient == null) {
			return 0;	
		} 
		
		HttpGet httpMethod = null;
		httpMethod = new HttpGet(url);
		
		try {
			
			HttpResponse response = httpClient.execute(httpMethod);
			responseCode = response.getStatusLine().getStatusCode();
			
			switch(responseCode) {
				case HttpStatus.SC_OK:
					//isResult = response.getEntity().getContent();
					//length = response.getEntity().getContentLength();
					strResult = EntityUtils.toString(response.getEntity()).trim();
					Log.i(TAG,"httpGet strResult="+strResult);
					break;
				case HttpStatus.SC_NOT_FOUND:

					result = -2;
					break;
				default:

					result = -2;
					break;
			}
			
		} catch (ClientProtocolException e) {
			result = -1;
			e.printStackTrace();
		} catch (IOException e) {
			result = -1;
			e.printStackTrace();
		} finally {
//			close();
		}
		
		return result;
	}
	
	/**
	 * 	执行  http post 方法
	 * 
	 * @param url	http 链接
	 * 
	 * @param postParams	post 数据
	 * 
	 * @return	返回方法执行状态
	 * 
	 * 			1 成功,0失败,-1异常,-2 responseCode != 200
	 * 
	 */
	public int httpPost(String url,Map<String, String> postParams) {
		
		int result = 1 ;
		
		if(url == null || url.length() <= 0) {
			return 0;
		}
		
		if(initHttpClient() == 0 || httpClient == null) {
			return 0;	
		} 
		
		HttpPost httpMethod = null;
		httpMethod = new HttpPost(url);
		
		try {
			
			//设置post数据
			if (postParams.size() > 0) {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				for (String name : postParams.keySet()) {
					params.add(new BasicNameValuePair(name, postParams.get(name)));
				}
				HttpEntity entity = new UrlEncodedFormEntity(params, mStrCode);
				httpMethod.setEntity(entity);
			}
			
			HttpResponse response = httpClient.execute(httpMethod);
			responseCode = response.getStatusLine().getStatusCode();
			
			switch(responseCode) {
				case HttpStatus.SC_OK:
					strResult = EntityUtils.toString(response.getEntity()).trim();
					Log.i(TAG,"httpPost strResult="+strResult);
					/*if(strResult!= null && strResult.length() > 0){
						strResult = Utils.replaceAngleBracket(strResult);
					}*/
					break;
				case HttpStatus.SC_NOT_FOUND:
					//do for 404 state 
					result = -2;
					break;
				default:
					//do default state
					result = -2;
					break;
			}
			
		} catch (ClientProtocolException e) {
			result = -1;
			e.printStackTrace();
		} catch (IOException e) {
			result = -1;
			e.printStackTrace();
		} finally {
//			close();
		}
		
		return result;
	}
	
	/**
	 * 	执行  http 方法
	 * 			
	 * 			兼容  get 和  post 
	 * 				
	 * 				当 postParams = null 时,执行get 
	 * 
	 * @param url	http 链接
	 * 
	 * @param postParams	post 数据
	 * 
	 * @return	返回方法执行状态
	 * 
	 * 			1 成功,0失败,-1异常,-2 responseCode != 200
	 * 
	 */
	public int excuteHttp(String url,Map<String, String> postParams) {
		
		int result = 1 ;
		
		if(url == null || url.length() <= 0) {
			return 0;
		}
		
		if(initHttpClient() == 0 || httpClient == null) {
			return 0;	
		} 
		
		HttpRequestBase httpMethod = null;
		
		try {
			
			//设置post数据
			if (postParams != null &&postParams.size() > 0 ) {
				HttpPost post = new HttpPost(url);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				for (String name : postParams.keySet()) {
					params.add(new BasicNameValuePair(name, postParams.get(name)));
				}
				HttpEntity entity = new UrlEncodedFormEntity(params, mStrCode);
				post.setEntity(entity);
				httpMethod = post;
			} else {
				httpMethod = new HttpGet(url);
			}
			
			HttpResponse response = httpClient.execute(httpMethod);
			responseCode = response.getStatusLine().getStatusCode();
			
			switch(responseCode) {
				case HttpStatus.SC_OK:
					strResult = EntityUtils.toString(response.getEntity()).trim();
					Log.i(TAG,"excuteHttp strResult="+strResult);
					break;
				case HttpStatus.SC_NOT_FOUND:
					//do for 404 state 
					result = -2;
					break;
				default:
					//do default state
					result = -2;
					break;
			}
			
		} catch (ClientProtocolException e) {
			result = -1;
			e.printStackTrace();
			Log.i("HttpProvider","result = -1;");
		} catch (IOException e) {
			result = -1;
			e.printStackTrace();
			Log.i("HttpProvider","result = 1");
		} finally {
			//close();
		}
		
		return result;
	}
	
	/**
	 * 关闭 httpClient
	 * 
	 */
	public void close() {
		if (httpClient != null) {
			try {
				httpClient.getConnectionManager().shutdown();
				httpClient = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}
